package com.example.pda.ui.stock;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;

import com.example.pda.R;
import com.example.pda.common.BaseActivity;
import com.example.pda.common.CommonCallback;
import com.example.pda.common.CompatUtil;
import com.example.pda.common.DaoUtils;
import com.example.pda.common.DialogUtils;
import com.example.pda.common.Utils;
import com.example.pda.data.Result;
import com.example.pda.data.model.GoodItem;
import com.example.pda.data.model.HwList;
import com.example.pda.data.model.Inventory;
import com.example.pda.data.model.StockList;
import com.example.pda.databinding.ActivityStockBinding;
import com.example.pda.view.ItemInputLayout;
import com.example.pda.view.SpinnerPopupView;

import java.io.Serializable;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import per.goweii.actionbarex.common.OnActionBarChildClickListener;

public class StockActivity extends BaseActivity {

    private static final String[] array = {
            "存货编码：",
            "存货名称：",
            "规格型号：",
            "入库仓库：",
            "入库货位：",
            "供应商批次：",
            "入库批次号：",
            "应到数量：",
            "应到数量：",
            "实到数量：",
            "备注：",
    };

    private static final String[] array2 = {
            "存货编码：",
            "存货名称：",
            "规格型号：",
            "出库仓库：",
            "出库货位：",
            "供应商批次：",
            "出库批次号：",
            "申请数量：",
            "可出数量：",
            "出库数量：",
            "备注：",
    };

    private static final String[] array3 = {
            "存货编码：",
            "存货名称：",
            "规格型号：",
            "出库仓库：",
            "出库货位：",
            "供应商批次：",
            "出库批次号：",
            "申请数量：",
            "可出数量：",
            "出库数量：",
            "备注：",
    };

    protected ActivityStockBinding binding;
    protected StockViewModel stockViewModel;

    protected ItemInputLayout mNumberLayout;
    protected ItemInputLayout mBzLayout;
    protected ItemInputLayout stockLayout;
    protected ItemInputLayout hwLayout;

    protected Inventory mCurBean;
    protected GoodItem mCurDataBean;
    protected boolean mIsLookMode;
    private String[] mTitles;
    private boolean isMode23;
    private boolean mIsScanData;

    public static void start(Context context, Inventory dada) {
        Intent intent = new Intent(context, StockActivity.class);
        intent.putExtra("BEAN", (Serializable) dada);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_stock);
        binding.setLifecycleOwner(this);
        stockViewModel = new ViewModelProvider(this, new StockViewModelFactory())
                .get(StockViewModel.class);

        mCurBean = (Inventory) getIntent().getSerializableExtra("BEAN");

        isMode23 = mCurBean.getBillType().equals("23");
        boolean mode4455 = mCurBean.getBillType().equals("4455");
        if (isMode23) {
            mTitles = array;
        } else if (mode4455) {
            mTitles = array2;
        } else {
            mTitles = array3;
        }
        mCurDataBean = CompatUtil.getInstance().getItemBean(CompatUtil.getInstance().getOtherIndex());
        if (mCurDataBean == null) {
            mCurDataBean = new GoodItem();
        }

        binding.scroller.setRecyclerView(binding.vrecyclerView);

        initScanEditView();
        initBottomBtn();
        initItemInputLayout(mCurDataBean);
        registerObserve(stockViewModel);
        stockViewModel.getDataLive().observe(this, new Observer<Result<GoodItem>>() {
            @Override
            public void onChanged(Result<GoodItem> result) {
                if (result instanceof Result.Success) {
                    if (result.getData().getType() > 0) {
                        DialogUtils.showInfoDialog(StockActivity.this, "该物料已添加入库，是否重复累加？", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                DialogUtils.closeInfoDialog();
                                mIsScanData = true;
                                mCurDataBean = result.getData();
                                float s1 = Float.parseFloat(mCurDataBean.getOriSl()) + Float.parseFloat(mCurDataBean.getSl());
                                mCurDataBean.setSl(String.valueOf(s1));
                                DaoUtils.getsUtils().insertDataList(mCurDataBean, 1);
                                initItemInputLayout(mCurDataBean);
                            }
                        }, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                DialogUtils.closeInfoDialog();
                                resetData();
                            }
                        });
                        return;
                    }
                    mIsScanData = true;
                    mCurDataBean = result.getData();
                    DaoUtils.getsUtils().insertDataList(mCurDataBean, 1);
                    initItemInputLayout(mCurDataBean);
                } else if (result instanceof Result.Error) {
                    Result.Error<GoodItem> error = (Result.Error<GoodItem>) result;
                    showCDialog(error.getMsg(), new CommonCallback<Object>() {
                        @Override
                        public void onResult(Object data, Object... objects) {
                            resetData();
                        }
                    });
                }
            }
        });
        stockViewModel.uploadResult.observe(this, new Observer<Result<Object>>() {
            @Override
            public void onChanged(Result<Object> objectResult) {
                if (objectResult instanceof Result.Success) {
                    showCDialog("上传成功", new CommonCallback<Object>() {
                        @Override
                        public void onResult(Object data, Object... objects) {
                            finish();
                        }
                    });
                } else {
                    showCDialog("上传失败:["+objectResult.getMsg()+"]", new CommonCallback<Object>() {
                        @Override
                        public void onResult(Object data, Object... objects) {

                        }
                    });
                }
            }
        });
    }

    private void initScanEditView() {
        // 存货编码|存货名称|规格型号|计量单位|数量|批次号|生产日期|供应商名称
//        binding.etCode.setText("0307050521|制冷剂CO2|R22|个|10|20220618|2022/07/02|徐州市新长晟化工有限公司");
//        binding.etCode.setText("0307050521|制冷剂CO2|制冷机RWFⅡ134E|个|4.5||2022/07/02|徐州市新长晟化工有限公司");
//        binding.etCode.setText("0403100126|方替代|制冷机RWFⅡ134E|个|200|1|2022/07/02|苏州硕普科林电子科技有限公司");
        binding.etCode.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    String code = binding.etCode.getText().toString();
                    Utils.LogI("code == " + code);
                    if (TextUtils.isEmpty(code)) {
                        Utils.LogI("ACTION_DOWN code is empty.");
                        showSoft();
                        return true;
                    }
                    binding.etCode.setText("");
                    addOrScan(code);
                }
                return true;
            }
        });
        binding.etCode.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                Utils.LogI("v hasFocus is " + hasFocus);
            }
        });
        showSoft();
    }

    private void addOrScan(String res) {
        hideSoft();
        if (!TextUtils.isEmpty(res)) {
            String[] all = res.replaceAll("\n", "").split("丨");
            if (all.length < 8) {
                all = res.replaceAll("\n", "").split("\\|");
            }
            try {
                if (all.length < 8) {
                    showDialog("扫码格式错误：" + res);
                    return;
                }
                // 存货编码|存货名称|规格型号|计量单位|数量|供应商批次号|生产日期|供应商名称
                GoodItem bean = new GoodItem();
                bean.setInvcode(all[0]);
                bean.setInvname(all[1]);
                bean.setGgxh(all[2]);
                bean.setSl(all[4]);
                bean.setGyspch(all[5]);
                bean.setGysname(all[7]);
                bean.setDjh(mCurBean.getDjh());
                stockViewModel.queryListByLocal(mCurBean.getBillType(), CompatUtil.getInstance().getItemList(), bean);
            } catch (Exception e) {
                e.printStackTrace();
                showDialog("二维码扫描解析异常，请联系管理员 e : " + e.getMessage());
            }
        } else {
            showDialog("扫描数据为空");
        }
    }

    private void initItemInputLayout(GoodItem goodItem) {
        if (goodItem == null) {
            goodItem = new GoodItem();
        }
        binding.scrollLayout.removeAllViews();
        binding.scrollLayout.addView(getItemInputLayout(0, mTitles[0], goodItem.getInvcode(), null));
        binding.scrollLayout.addView(getItemInputLayout(1, mTitles[1], goodItem.getInvname(), null));
        binding.scrollLayout.addView(getItemInputLayout(2, mTitles[2], goodItem.getGgxh(), null));

        if (!Utils.isEmpty(goodItem.getStockList())) {
            GoodItem finalGoodItem = goodItem;
            stockLayout = getItemInputLayout(3, mTitles[3], goodItem.getBstockname(), new ItemInputLayout.ItemLayoutListener() {
                @Override
                public void onItemEditClick(ItemInputLayout layout, Object... objects) {
                    new SpinnerPopupView<>(binding.scroller, layout, binding.vrecyclerView, finalGoodItem.getStockList(), finalGoodItem.getBstockcode(), new CommonCallback<StockList>() {
                        @Override
                        public void onResult(StockList data, Object... objects) {
                            if (data == null) {
                                updateSpinnerData(layout, new StockList(), -1);
                                return;
                            }
                            updateSpinnerData(layout, data, (int) objects[0]);
                        }
                    });
                }
            }, ItemInputLayout.MODE_SPINNER);
        } else {
            stockLayout = getItemInputLayout(3, mTitles[3], goodItem.getBstockname(), null, ItemInputLayout.MODE_TEXT);
        }
        if (!Utils.isEmpty(goodItem.getHwList())) {
            GoodItem finalGoodItem1 = goodItem;
            hwLayout = getItemInputLayout(4, mTitles[4], goodItem.getBhwname(), new ItemInputLayout.ItemLayoutListener() {
                @Override
                public void onItemEditClick(ItemInputLayout layout, Object... objects) {
                    new SpinnerPopupView<>(binding.scroller, layout, binding.vrecyclerView, finalGoodItem1.getHwList(), finalGoodItem1.getBhwcode(), new CommonCallback<HwList>() {
                        @Override
                        public void onResult(HwList data, Object... objects) {
                            if (data == null) {
                                updateSpinnerData(layout, new HwList(), -1);
                                return;
                            }
                            updateSpinnerData(layout, data, (int) objects[0]);

                        }
                    });
                }
            }, ItemInputLayout.MODE_SPINNER);
        } else {
            hwLayout = getItemInputLayout(4, mTitles[4], goodItem.getBhwname(), null, ItemInputLayout.MODE_TEXT);
        }
        binding.scrollLayout.addView(stockLayout);
        binding.scrollLayout.addView(hwLayout);
        binding.scrollLayout.addView(getItemInputLayout(5, mTitles[5], goodItem.getGyspch(), null));
        binding.scrollLayout.addView(getItemInputLayout(6, mTitles[6], goodItem.getPch(), null));
        if (!isMode23) {
            binding.scrollLayout.addView(getItemInputLayout(7, mTitles[7], goodItem.getYcsl(), null));
        }
        binding.scrollLayout.addView(getItemInputLayout(8, mTitles[8], goodItem.getHgsl(), null));
        mNumberLayout = getItemInputLayout(9, mTitles[9], goodItem.getSl(),
                null, ItemInputLayout.MODE_EDIT, true);
        mBzLayout = getItemInputLayout(10, mTitles[10], goodItem.getBz(), null, ItemInputLayout.MODE_EDIT);
        binding.scrollLayout.addView(mNumberLayout);
        binding.scrollLayout.addView(mBzLayout);
    }


    private void initBottomBtn() {
        binding.btnPre.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clickHandler(-1);
            }
        });
        binding.btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                clickHandler(0);
            }
        });
        binding.btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clickHandler(1);
            }
        });
        binding.abc.setOnRightTextClickListener(new OnActionBarChildClickListener() {
            @Override
            public void onClick(View v) {
                clickHandler(2);
            }
        });
    }

    public String getValue(String str) {
        return TextUtils.isEmpty(str) ? "" : str;
    }

    private void clickHandler(int event) {
        if (mIsScanData && event != 0) {
            saveData();
        }
        mIsScanData = false;
        GoodItem items;
        switch (event) {
            case 1:
                items = CompatUtil.getInstance().getOther(event);
                if (items != null) {
                    mCurDataBean = items;
                    mIsLookMode = true;
                    initItemInputLayout(mCurDataBean);
                    showSoft();
                } else {
                    Utils.getInstance().showToast("没有下一页了");
                }
                showSoft();
                break;
            case -1:
                items = CompatUtil.getInstance().getOther(event);
                if (items != null) {
                    mCurDataBean = items;
                    mIsLookMode = true;
                    initItemInputLayout(mCurDataBean);
                } else {
                    Utils.getInstance().showToast("没有上一页了");
                }
                showSoft();
                break;
            case 2:
                // 上传
                List<GoodItem> uploadItems = DaoUtils.getsUtils().getGoodItemAll(mCurBean.getDjh());
                if (Utils.isEmpty(uploadItems)) {
                    Utils.getInstance().showToast("暂无需要上传的数据");
                    return;
                }
                stockViewModel.upload(mCurBean, uploadItems);
                break;
            default:
                // 保存
                saveData();
                CompatUtil.getInstance().resetCurIndex(mCurBean.getDjh());
                resetData();
                break;
        }
    }

    private void showSoft() {
        binding.etCode.requestFocus();
        binding.etCode.setFocusable(true);
        binding.etCode.setFocusableInTouchMode(true);
        InputMethodManager imm = (InputMethodManager) binding.etCode.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(binding.etCode, 0);
    }

    private void hideSoft() {
        binding.etCode.requestFocus();
        InputMethodManager imm = (InputMethodManager) binding.etCode.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(binding.etCode.getWindowToken(), 0);
    }

    private <T> void updateSpinnerData(ItemInputLayout layout, T t, int which) {
        if (t instanceof HwList) {
            layout.getBinding().evValue.setText(((HwList) t).getHwname());
            if (mCurDataBean != null) {
                mCurDataBean.setBhwcode(((HwList) t).getHwcode());
                mCurDataBean.setBhwname(((HwList) t).getHwname());
                mCurDataBean.setBhwIndex(which);
            }
        } else if (t instanceof StockList) {
            layout.getBinding().evValue.setText(((StockList) t).getStockname());
            if (mCurDataBean != null) {
                mCurDataBean.setBstockcode(((StockList) t).getStockcode());
                mCurDataBean.setBstockname(((StockList) t).getStockname());
                mCurDataBean.setBstockIndex(which);
            }
        }
    }

    private void showDialog(String msg) {
        showCDialog(msg, null);
    }

    private void showCDialog(String msg, CommonCallback<Object> commonCallback) {
        DialogUtils.showInfoDialog(this, msg, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                DialogUtils.closeInfoDialog();
                if (commonCallback != null) {
                    commonCallback.onResult(new Object());
                } else {
                    resetData();
                }
            }
        });
    }

    private void saveData() {
        if (mCurDataBean != null && !TextUtils.isEmpty(mCurDataBean.getSl())) {
            if (!TextUtils.isEmpty(mNumberLayout.getItemValue())) {
                mCurDataBean.setSl(mNumberLayout.getItemValue());
            }
            if (!TextUtils.isEmpty(mBzLayout.getItemValue())) {
                mCurDataBean.setBz(mBzLayout.getItemValue());
            }
            DaoUtils.getsUtils().insertDataList(mCurDataBean, 1);
        }
    }

    private void resetData() {
        StockActivity.start(this, mCurBean);
        finish();
    }

    private ItemInputLayout getItemInputLayout(int index, String name, String value,
                                               ItemInputLayout.ItemLayoutListener listener) {
        return getItemInputLayout(index, name, value, listener, ItemInputLayout.MODE_TEXT, false);
    }

    private ItemInputLayout getItemInputLayout(int index, String name, String value,
                                               ItemInputLayout.ItemLayoutListener listener, int mode) {
        return getItemInputLayout(index, name, value, listener, mode, false);
    }

    private ItemInputLayout getItemInputLayout(int index, String name, String value,
                                               ItemInputLayout.ItemLayoutListener listener, int mode, boolean isNumber) {
        ItemInputLayout inputLayout = new ItemInputLayout(this);
        inputLayout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        inputLayout.getBinding().setTitle(name);
        inputLayout.getBinding().evValue.setText(TextUtils.isEmpty(value) ? "" : value);
        if (isNumber) {
            inputLayout.getBinding().evValue.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
        }
        inputLayout.setItemMode(listener, mode);
        inputLayout.setIndex(index);
        return inputLayout;
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (mIsScanData) {
            saveData();
        }
    }

}